//
//  FindViewController.m
//  LittleFairyPoet
//
//  Created by rimi on 15/9/9.
//  Copyright (c) 2015年 周林. All rights reserved.
//

#import "DirectoryViewController.h"
#import "ZLDetailPoemViewController.h"
#import "UIImage+Clips.h"
#import <DCPathButton.h>
#import <ReactiveCocoa.h>

typedef NS_ENUM(NSUInteger, ZLFilterButtonClicked) {
    ZLFilterButtonClickedLvshi,
    ZLFilterButtonClickedJueju,
    ZLFilterButtonClickedGuwen,
    ZLFilterButtonClickedSearch
};

static NSString *const kUITableViewCellIdentifier = @"cellIdentifier";

@interface DirectoryViewController () <UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, DCPathButtonDelegate, UISearchResultsUpdating>


@property (nonatomic, strong) UITableView * resultTabView;
@property (nonatomic, strong) NSMutableArray * searchDataSource;/**< 数据源 */
@property (nonatomic, strong) NSMutableArray * dataSource;/**< 初始化的数据源 */
@property (nonatomic, strong) UISearchController * searchController;
@property (nonatomic, strong) NSMutableArray * resultArray;
@property (nonatomic, strong) DCPathButton * filterButton /**<  */;
@property (nonatomic, assign) BOOL isSearch;

- (void)initializeDataSource; /**< 初始化数据源 */
- (void)initializeUserInterface; /**< 初始化用户界面 */

@end

@implementation DirectoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeUserInterface];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    _isSearch = NO;
    // 将搜索栏是否隐藏置为NO。
    self.searchController.searchBar.hidden = NO;
    // 将搜索控制器是否活动置为NO。
    self.searchController.active = NO;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
    
}

#pragma mark - private methods
- (void)initializeDataSource {

    NSString * plistPath = [[NSBundle mainBundle]pathForAuxiliaryExecutable:@"绝句.plist"];
    _dataSource = [NSMutableArray arrayWithContentsOfFile:plistPath];
    _searchDataSource = [NSMutableArray arrayWithArray:_dataSource];
}
- (void)initializeUserInterface {
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.titleLable.text = @"学习";
    self.baseNavigationBar.backgroundColor = [UIColor clearColor];
    CALayer *layer = [CALayer layer];
    layer.bounds = self.view.bounds;
    layer.position = self.view.center;
    layer.contents = (__bridge id)(IMAGE_CONTENT(@"目录背景.jpg")).CGImage;
    [self.view.layer addSublayer:layer];
    self.rightButton.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.resultTabView];
    
    
   
    [self.baseNavigationBar removeFromSuperview];
    self.baseNavigationBar.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.baseNavigationBar];
    [self.view addSubview:self.filterButton];
}
#pragma mark---responds events
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    //收起键盘点击其他地方
    [self.view endEditing:YES];
    [self.resultTabView endEditing:YES];
}

#pragma mark - 系统协议
- (NSArray*)visibleCells
{
    return [self.resultTabView visibleCells];
}


#pragma mark---协议UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  _isSearch ? _resultArray.count:_searchDataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kUITableViewCellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kUITableViewCellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryNone;
    if (!_isSearch) {
        cell.textLabel.text = _searchDataSource[indexPath.row][@"title"];
        cell.textLabel.font = [UIFont fontWithName:@"Kaiti" size:18];
        NSString * detailStr = [NSString stringWithFormat:@"%@·%@%ld",_searchDataSource[indexPath.row][@"zuozhe"], _searchDataSource[indexPath.row][@"chaodai"], indexPath.row];
        cell.detailTextLabel.text = detailStr;
        cell.detailTextLabel.font = [UIFont fontWithName:@"Kaiti" size:16];
        cell.backgroundColor = [UIColor clearColor];
    } else {
        cell.textLabel.text = _resultArray[indexPath.row][@"title"];
        cell.textLabel.font = [UIFont fontWithName:@"Kaiti" size:18];
        NSString * detailStr = [NSString stringWithFormat:@"%@·%@ %ld",_resultArray[indexPath.row][@"zuozhe"], _resultArray[indexPath.row][@"chaodai"], indexPath.row];
        cell.detailTextLabel.text = detailStr;
        cell.detailTextLabel.font = [UIFont fontWithName:@"Kaiti" size:16];
        cell.backgroundColor = [UIColor clearColor];
    }
    
    return cell;
}
#pragma mark - UITableViewDataSource

//设置每一行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

//用户点击了某一行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!self.isFind) {
        ZLDetailPoemViewController * detailVC = [[ZLDetailPoemViewController alloc]init];
        if (_isSearch) {
            detailVC.poemDic = _resultArray[indexPath.row];
            detailVC.poemArray = _resultArray;
        } else {
            detailVC.poemDic = _searchDataSource[indexPath.row];
            detailVC.poemArray = _searchDataSource;
        }
        detailVC.poemSerialNo = indexPath.row;
        detailVC.indexPath = indexPath;
        [self.view endEditing:YES];
        [self.navigationController pushViewController:detailVC animated:YES];
        
    } else {
        if (self.planPeoms.count > 10) {
            [self initializeAlertControllerWithMessage:@"已超过10首了呢，请不要给孩子太多压力喔"];
            return;
        }
        NSString * title = _searchDataSource[indexPath.row][@"title"];
        if (self.planPeoms.count > 0) {
            for (NSDictionary * obj in self.planPeoms) {
                if ([title isEqualToString:obj[@"title"]]) {
                    [self initAlertControllerDismissWithMessage:@"已存在"];
                    return;
                }
            }
        }
        [self.view endEditing:YES];
        [self.planPeoms addObject:_searchDataSource[indexPath.row]];
        [self initAlertControllerDismissWithMessage:@"已添加"];
        
    }
}
#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    if (!searchController.active) {
        _isSearch = NO;
        [self.resultTabView reloadData];
        return;
    }
    _isSearch = YES;
    NSString * findString = searchController.searchBar.text;
    _resultArray = [NSMutableArray new];
    for (NSDictionary * dict in _dataSource) {
        if ([dict[@"title"] containsString:findString]|[dict[@"zuozhe"] containsString:findString]) {
            [_resultArray addObject:dict];
        }
    }
    [self.resultTabView reloadData];
    
}
#pragma mark - <DCPathButtonDelegate>
- (void)pathButton:(DCPathButton *)dcPathButton clickItemButtonAtIndex:(NSUInteger)itemButtonIndex {
    
    switch (itemButtonIndex) {
        case ZLFilterButtonClickedJueju:
        {
            NSString *juejuPath = [[NSBundle mainBundle]pathForAuxiliaryExecutable:@"绝句.plist"];
            _searchDataSource = [NSMutableArray arrayWithContentsOfFile:juejuPath];
            [self.resultTabView reloadData];
        }
            break;
        case ZLFilterButtonClickedLvshi:
        {
            NSString *lvShiPath = [[NSBundle mainBundle]pathForAuxiliaryExecutable:@"律诗.plist"];
            _searchDataSource = [NSMutableArray arrayWithContentsOfFile:lvShiPath];
            [self.resultTabView reloadData];
        }
            break;
        case ZLFilterButtonClickedGuwen:
        {
            NSString *lvShiPath = [[NSBundle mainBundle]pathForAuxiliaryExecutable:@"古文.plist"];
            _searchDataSource = [NSMutableArray arrayWithContentsOfFile:lvShiPath];
            [self.resultTabView reloadData];
        }
            break;
        default:
            break;
    }
}

#pragma mark - getter
- (UISearchController *)searchController {
    if (!_searchController) {
        _searchController = ({
            UISearchController * searchVC = [[UISearchController alloc]initWithSearchResultsController:nil];
            searchVC.searchBar.frame = DHFlexibleFrame(CGRectMake(0, 0, 320, 40), YES);
            searchVC.hidesNavigationBarDuringPresentation = NO;
            searchVC.dimsBackgroundDuringPresentation = NO;
            searchVC.searchBar.placeholder = @"请输入作品名或者作者名搜索";
            searchVC.searchResultsUpdater = self;
            searchVC.searchBar.backgroundImage = IMAGE_CONTENT(@"搜索框背景.png");
            searchVC;
        });
    }
    return _searchController;
}
- (UITableView *)resultTabView {
    if (!_resultTabView) {
        _resultTabView = ({
            UITableView * tableview = [[UITableView alloc]initWithFrame:DHFlexibleFrame(CGRectMake(0, 55, ORIGIN_WIDTH, ORIGIN_HEIGHT- 55), NO) style:UITableViewStylePlain];
            tableview.separatorColor = ZLColor(48, 121, 33);
            tableview.dataSource = self;
            tableview.delegate = self;
            tableview.tableFooterView = [UIView new];
            tableview.pagingEnabled = NO;
            tableview.bounces = NO;
            tableview.backgroundColor = [UIColor clearColor];
            tableview.tableHeaderView = self.searchController.searchBar;
            tableview;
        });
    }
    return _resultTabView;
}
- (NSMutableArray *)planPeoms {
    if (!_planPeoms) {
        _planPeoms = [NSMutableArray array];
    }
    return _planPeoms;
}

- (DCPathButton *)filterButton {
    if (!_filterButton) {
        _filterButton = [[DCPathButton alloc]initWithButtonFrame:DHFlexibleFrame(CGRectMake(290, 540, 40, 40), NO) centerImage:[UIImage imageWithImage:IMAGE_WITH_NAME(@"漏斗.png") radius:40] highlightedImage:nil];
        DCPathItemButton *lvshiButton = [[DCPathItemButton alloc]initWithImage:[UIImage imageWithImage:IMAGE_WITH_NAME(@"律诗.png") radius:45] highlightedImage:nil backgroundImage:nil backgroundHighlightedImage:nil];
        DCPathItemButton *juejuButton = [[DCPathItemButton alloc]initWithImage:[UIImage imageWithImage:IMAGE_WITH_NAME(@"绝句.png") radius:45] highlightedImage:nil backgroundImage:nil backgroundHighlightedImage:nil];
        DCPathItemButton *guwenButton = [[DCPathItemButton alloc]initWithImage:[UIImage imageWithImage:IMAGE_WITH_NAME(@"古文.png") radius:45] highlightedImage:nil backgroundImage:nil backgroundHighlightedImage:nil];
        _filterButton.delegate = self;
        _filterButton.bloomDirection = kDCPathButtonBloomDirectionTopLeft;
        [_filterButton addPathItems:@[lvshiButton, juejuButton, guwenButton]];
    }
    return _filterButton;
}


@end
